<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getFinanceStatisticsAPI, deleteFinanceRecordAPI } from '@/pagesOrgan/services/finance'
import type { FinanceStatistics, FinanceRecord } from '@/types/finance'
import FinanceRecordItem from './components/FinanceRecordItem.vue'

const statistics = ref<FinanceStatistics | null>(null)
const isLoading = ref(true)
const recentRecords = ref<FinanceRecord[]>([])

// 获取财务统计数据
const fetchStatistics = async () => {
  try {
    isLoading.value = true
    const now = new Date()
    const startDate = `${now.getFullYear()}-01-01`
    const endDate = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`
    const res = await getFinanceStatisticsAPI({
      startDate,
      endDate,
      pageSize: 10,
      pageNum: 1,
    })
    statistics.value = res.data
    recentRecords.value = res.data.dailyData
  } catch (error) {
    console.error('获取财务统计数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 处理记录点击事件
const handleRecordClick = (record: FinanceRecord) => {
  uni.navigateTo({
    url: `/pagesOrgan/finance/add?id=${record.id}&type=${record.expenseType}`,
  })
}

// 处理记录删除事件
const handleRecordDelete = async (id: string) => {
  // 实际项目中应该调用API删除记录
  // 这里仅做前端演示
  const confirmRes = await uni.showModal({
    title: '确认删除',
    content: '确定要删除这条记录吗？',
  })

  if (confirmRes.confirm) {
    try {
      await deleteFinanceRecordAPI(id)
      recentRecords.value = recentRecords.value.filter((record) => record.id !== id)
      uni.showToast({ title: '删除成功', icon: 'success' })
    } catch (error) {
      console.error('删除记录失败:', error)
      uni.showToast({ title: '删除失败', icon: 'error' })
    }
  }
}

onMounted(() => {
  fetchStatistics()
})

// 跳转到收入记录页
const navigateToIncome = () => {
  uni.navigateTo({
    url: '/pagesOrgan/finance/income',
  })
}

// 跳转到支出记录页
const navigateToExpense = () => {
  uni.navigateTo({
    url: '/pagesOrgan/finance/expense',
  })
}

// 跳转到添加记录页
const navigateToAddRecord = () => {
  uni.navigateTo({
    url: '/pagesOrgan/finance/add?type=2',
  })
}

// 跳转到统计页
const navigateToStatistics = () => {
  uni.navigateTo({
    url: '/pagesOrgan/finance/statistics',
  })
}
</script>

<template>
  <scroll-view class="page-container" scroll-y>
    <!-- 顶部统计卡片 -->
    <view class="stat-container">
      <view class="stat-card total-income">
        <text class="stat-label">总收入</text>
        <text class="stat-value">{{ statistics?.totalIncome || 0 }}元</text>
      </view>
      <view class="stat-card total-expense">
        <text class="stat-label">总支出</text>
        <text class="stat-value">{{ statistics?.totalExpense || 0 }}元</text>
      </view>
      <view class="stat-card net-profit">
        <text class="stat-label">净利润</text>
        <text class="stat-value">{{ statistics?.netProfit || 0 }}元</text>
      </view>
    </view>

    <!-- 功能入口 -->
    <view class="function-grid">
      <view class="function-item" @click="navigateToIncome">
        <image class="function-icon" src="/static/images/income.png"></image>
        <text class="function-name">收入记录</text>
      </view>
      <view class="function-item" @click="navigateToExpense">
        <image class="function-icon" src="/static/images/expense.png"></image>
        <text class="function-name">支出记录</text>
      </view>
      <view class="function-item" @click="navigateToStatistics">
        <image class="function-icon" src="/static/images/statistics.png"></image>
        <text class="function-name">财务统计</text>
      </view>
    </view>

    <!-- 近期收支 -->
    <view class="recent-records">
      <view class="section-header">
        <text class="section-title">近期收支</text>
      </view>
      <view class="record-list">
        <block v-if="recentRecords.length > 0">
          <finance-record-item
            v-for="record in recentRecords"
            :key="record.id"
            :record="record"
            @click="handleRecordClick"
            @delete="handleRecordDelete"
          />
        </block>
        <view
          class="no-data"
          v-else-if="!isLoading && (!statistics || statistics.dailyData.length === 0)"
        >
          <text>暂无收支记录</text>
        </view>
      </view>
    </view>

    <!-- 底部添加按钮 -->
    <view class="add-btn" @click="navigateToAddRecord">
      <image class="add-icon" src="@/static/images/add.png"></image>
    </view>
  </scroll-view>
</template>

<style lang="scss">
.page-container {
  height: 100vh;
  padding: 20rpx;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.stat-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.stat-card {
  width: 32%;
  padding: 20rpx;
  border-radius: 10rpx;
  text-align: center;
}

.total-income {
  background-color: #e6f7ff;
}

.total-expense {
  background-color: #fff2f0;
}

.net-profit {
  background-color: #f0fff4;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
}

.total-income .stat-value {
  color: #409eff;
}

.total-expense .stat-value {
  color: #f56c6c;
}

.net-profit .stat-value {
  color: #67c23a;
}

.function-grid {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.function-item {
  width: 32%;
  background-color: #fff;
  padding: 20rpx 0;
  border-radius: 10rpx;
  text-align: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.function-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

.function-name {
  font-size: 26rpx;
  color: #333;
}

.recent-records {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 120rpx; /* 为底部添加按钮留出空间 */
}

.section-header {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.record-list {
  background-color: #fff;
  border-radius: 10rpx;
  overflow: hidden;
}

.no-data {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

.add-btn {
  position: fixed;
  bottom: 60rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #409eff;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 60rpx;
  box-shadow: 0 4rpx 20rpx rgba(64, 158, 255, 0.5);
  .add-icon {
    width: 40rpx;
    height: 40rpx;
    margin-bottom: 8rpx;
  }
}

/* 响应式适配 */
@media screen and (max-width: 320px) {
  .stat-card {
    padding: 15rpx 10rpx;
  }

  .stat-value {
    font-size: 30rpx;
  }

  .function-name {
    font-size: 24rpx;
  }
}
</style>
